package org.leiyang.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import io.reactivex.Flowable;
import org.leiyang.domain.dtos.Prompts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import org.leiyang.service.impls.InvokeAPIServiceImpl;

import java.time.Duration;

/**
 * SSE（Server-Sent Events）方式交互
 */
@RestController
@RequestMapping("/sse")
public class TalkBySSEController {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    private final InvokeAPIServiceImpl invokeAPIService;

    public TalkBySSEController(InvokeAPIServiceImpl invokeAPIService) {
        this.invokeAPIService = invokeAPIService;
    }

    /**
     * 测试接口
     */
    @PostMapping(value = "/conversation/test", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> conversationTest(@RequestBody Prompts prompts) {
        logger.info("服务端收到的question: {}", prompts.getQuestion());
        return Flux.interval(Duration.ofSeconds(1))
                .takeUntil(sequence -> sequence >= 6L)
                .map(sequence -> "Event " + sequence + "\n");
    }

    /**
     * 对接真实big module
     * @param prompts 用户提出的问题
     */
    @PostMapping(value = "/conversation", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flowable<String> conversation(@RequestBody Prompts prompts) throws JsonProcessingException {
        logger.info("服务端收到的question: {}", prompts.getQuestion());
        return invokeAPIService.LLMAPIInvokeSSE(prompts.getQuestion());
    }

}